from django.shortcuts import render
from django.http import HttpResponse
import datetime

from .forms import StudentForm
from .models import Student
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.db.models import Q


class StudentListView(ListView):
    """显示学生列表的类视图"""
    model = Student
    template_name = 'myapp/student_list.html'
    context_object_name = 'students'  # 模板中使用的变量名
    paginate_by = 5  # 每页显示5条记录
    ordering = ['-id']  # 按ID倒序排列

    def get_queryset(self):
        """重写查询集，添加搜索功能"""
        queryset = super().get_queryset()
        search_query = self.request.GET.get('q')

        if search_query:
            queryset = queryset.filter(
                Q(name__icontains=search_query) |
                Q(student_id__icontains=search_query)
            )
        return queryset

    def get_context_data(self, **kwargs):
        """添加上下文数据"""
        context = super().get_context_data(**kwargs)
        context['title'] = '学生信息管理系统'
        context['search_query'] = self.request.GET.get('q', '')
        return context



def hello(request):
    """简单的视图函数，返回Hello World"""
    return HttpResponse("Hello, Django Learner! 🎉")


def welcome(request):
    """显示欢迎页面的视图函数"""
    context = {
        'current_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        'visit_count': 1
    }
    return render(request, 'myapp/welcome.html', context)


from django.db.models import Q

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def student_list(request):
    """显示所有学生的视图函数，支持搜索和分页"""
    students = Student.objects.all().order_by('-id')

    # 处理搜索
    search_query = request.GET.get('q', '')
    if search_query:
        students = students.filter(
            Q(name__icontains=search_query) |
            Q(student_id__icontains=search_query)
        )

    # 分页 - 每页显示5条记录
    paginator = Paginator(students, 5)
    page = request.GET.get('page')

    try:
        students_page = paginator.page(page)
    except PageNotAnInteger:
        # 如果page参数不是整数，显示第一页
        students_page = paginator.page(1)
    except EmptyPage:
        # 如果页数超出范围，显示最后一页
        students_page = paginator.page(paginator.num_pages)

    context = {
        'students': students_page,
        'title': '学生信息管理系统',
        'search_query': search_query
    }
    return render(request, 'myapp/student_list.html', context)



def student_add(request):
    """添加学生的视图函数 - 使用Django表单"""
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            # 表单验证通过，保存数据
            student = form.save()
            messages.success(request, f'学生 {student.name} 添加成功！')
            return redirect('student_list')
        else:
            # 表单验证失败，显示错误信息
            messages.error(request, '请检查表单中的错误！')
    else:
        # GET请求，显示空表单
        form = StudentForm()

    return render(request, 'myapp/student_form.html', {
        'form': form,
        'title': '添加学生',
        'form_type': 'add'
    })


def student_edit(request, student_id):
    """编辑学生的视图函数 - 使用Django表单"""
    student = get_object_or_404(Student, id=student_id)

    if request.method == 'POST':
        form = StudentForm(request.POST, instance=student)
        if form.is_valid():
            student = form.save()
            messages.success(request, f'学生 {student.name} 信息更新成功！')
            return redirect('student_list')
        else:
            messages.error(request, '请检查表单中的错误！')
    else:
        # GET请求，用学生数据填充表单
        form = StudentForm(instance=student)

    return render(request, 'myapp/student_form.html', {
        'form': form,
        'title': '编辑学生',
        'form_type': 'edit',
        'student': student
    })

def student_delete(request, student_id):
    """删除学生的视图函数"""
    student = get_object_or_404(Student, id=student_id)

    if request.method == 'POST':
        # 确认删除
        student_name = student.name
        student.delete()
        messages.success(request, f'学生 {student_name} 已成功删除！')
        return redirect('student_list')

    # GET请求时显示确认页面
    return render(request, 'myapp/student_confirm_delete.html', {
        'student': student
    })